<?php

namespace app\common\traits;

trait Backend
{
    public function index()
    {
        if($this->request->isAjax()){
            list($where, $sort, $order, $offset, $limit) = $this->buildParameter();
            $is_tree = $this->request->param('isTree',0);
            if($is_tree){
                $list = $this->model->where($where)
                    ->order('pid','asc')
                    ->order($sort, $order)
                    ->select()->toArray();
//                echo '<pre>';
//                print_r($list);
//                exit;
                $pk = $this->model->getPk();
                $pid_field = $this->request->param('pid_field','pid');
                if(empty($pid_field)){
                    $pid_field = 'pid';
                }
                if(!empty($list)){
                    $min = min(array_column($list,$pid_field));
                    $list = list_to_tree($list,$pk,$pid_field,'children',$min);
                }
                if($this->index_get_data){
                    return [
                        'total' => count($list),
                        'rows' => $list,
                    ];
                }
                return $this->success("获取成功", [
                    'total' => count($list),
                    'rows' => $list,
                ]);
            }else{
                $list = $this->model->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }
            if($this->index_get_data){
                return [
                    'total' => $list->total(),
                    'rows' => $list->items(),
                ];
            }
            return $this->success("获取成功", [
                'total' => $list->total(),
                'rows' => $list->items(),
            ]);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if($this->request->isAjax()){
            $data = $this->request->param('row/a');
            $res = $this->model->save($data);
            if($res){
                return $this->success("添加成功");
            }else{
                return $this->error("添加失败");
            }
        }
        return $this->view->fetch();
    }
    public function edit($ids=null)
    {
        if(empty($ids)){
            $ids = $this->request->param('ids');
        }
        $row = $this->model->field($this->editField)->find($ids);
        if($this->request->isAjax()){
            $data = $this->request->param('row/a');
            $res = $row->save($data);
            if($res){
                return $this->success("修改成功");
            }else{
                return $this->error("修改失败");
            }
        }
        $this->assignconfig('row',$row);
        return $this->view->fetch();
    }
    public function del($ids=null)
    {
        if(empty($ids)){
            $ids = $this->request->param('ids');
        }
        if(empty($ids)){
            return $this->error("删除失败");
        }
        $ids = $this->model->whereIn($this->model->getPk(),$ids)->column($this->model->getPk());
        if(empty($ids)){
            return $this->error("删除失败");
        }
        $res = $this->model->destroy($ids);
        if ($res){
            return $this->success("删除成功");
        }
        return $this->error("删除失败");
    }
    public function buildParameter($whereIsArray=false)
    {
        $relationSearch = $this->relationSearch;

        $sort = $this->request->param('sort',
            ! empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->param('order', 'DESC');
        $page = $this->request->param('page', 1);
        if(empty($page)){
            $page = 1;
        }
        $limit = $this->request->param('limit', 10);
        if(empty($limit)){
            $limit = 10;
        }
        $offset = $this->request->param('offset',null);
        if($offset==null){
            $offset = ($page-1)*$limit;
        }
        $where = [];
        $filter = $this->request->param('filter',[]);
        $op = $this->request->param('op',[]);
        foreach ($filter as $k=>$v){
            $sym = isset($op[$k]) ? $op[$k] : ' = ';
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym){
                case ' = ':
                case '=':
                case ' <> ':
                case '<>':
                    $where[] = [$k, $sym, (string) $v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace(' %...%', '', $sym)), "%{$v}%"];
                    break;
                case ' > ':
                case '>':
                case '>=':
                case ' < ':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('$v', ".($relationSearch ? $k : '`'.str_replace('.', '` . `', $k).'`').')';
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    if(is_string($v)){
                        $arr = array_slice(explode(',', $v), 0, 2);
                        if (stripos($v, ',') === false || !array_filter($arr, function($v){
                                return $v != '' && $v !== false && $v !== null;
                            })) {
                            continue 2;
                        }
                    }else{
                        $v = array_filter($v);
                        if(empty($v)){
                            continue 2;
                        }
                        $arr = $v;
                    }

                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? ' <= ' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? ' >= ' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || ! array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? ' <= ' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? ' >= ' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym).' time', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        if($whereIsArray===false){
            if (! empty($where)) {
                $where = function ($query) use ($where) {
                    foreach ($where as $k => $v) {
                        if (is_array($v)) {
                            call_user_func_array([$query, 'where'], $v);
                        } else {
                            $query->where($v);
                        }
                    }
                };
            }
        }


        return [$where, trim($sort), trim($order), $offset, $limit];
    }
    public function multi($ids=null)
    {
        if(empty($ids)){
            $ids = $this->request->param('ids');
        }
        if(empty($ids)){
            return $this->error("请选择要操作的数据");
        }
        $field = $this->request->param('field','status');
        if(empty($field)){
            $field  = 'status';
        }
        $row = $this->model->where($this->model->getPk(),$ids)->find();
        if(empty($row)){
            return $this->error("数据不存在");
        }
        $row->$field = $row->$field==1 ? 0 : 1;
        $res = $row->save();
        if($res){
            return $this->success("操作成功");
        }else{
            return $this->error("操作失败");
        }
    }
}